/**
 *Author: chenxiaoyu
 *Date: 2018/4/3
 *Email: 1524904743@qq.com
 *
 */

(function () {
    /*
    * 首页标签选择指令封装
    * */
    app.directive('umark', [function () {
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                marks: '='
            },
            templateUrl: '/client/components/index/template/umark.html',
            link: function ($scope, element, attrs) {
                $scope.marks= [{name: '产品', id: 1, stype: 'd', list: [{name: 'app', type: '产品'}, {name: 'web', type: '产品'}]},
                    {name: '机构', id: 2, stype: 'd', list: [{name: '平安', type: '机构'},{name: '中行', type: '机构'}]}];
                $scope.showIndex= -1;
                $scope.stype= 'd';  //  多选d，单选s
                $scope.sId= -1;
                $scope.marksed= []; // 选中标签的数组
                $scope.markseding= [];  // 选中标签临时数组

                // 收起标签列表
                $scope.hideMarks= function () {
                    $scope.showIndex= -1;
                    var obj= element.find('.mark-list');
                    if (obj.css('overflow') === 'hidden'){
                        obj.css('overflow', 'inherit').css('height', 'auto');
                    }else {
                        obj.css('overflow', 'hidden').css('height', '25px');
                    }
                }

                // 打开标签列表
                $scope.openMore= function (i, t) {
                    if (!!t && t == 'd'){
                        $scope.marks[i].stype= 's';
                    }else if(!!t && t == 's'){
                        $scope.marks[i].stype= 'd';
                    }else{
                        if ($scope.showIndex == -1){
                            $scope.showIndex= i;
                            $scope.markseding= [];
                        }else {
                            $scope.showIndex= $scope.showIndex == i? -1: i;
                        }
                    }
                }
                
                // 标签选择事件
                $scope.marksClick= function (o, t) {
                    if (t == 's'){
                        if ($scope.marksed.indexOf(o) == -1){
                            var b= true;
                            var k= '';
                                angular.forEach($scope.marksed, function (item, k) {
                                if(o.type == item.type){
                                    b= false;
                                    k= k;
                                }
                            })
                            if (b){
                                $scope.marksed.push(o);
                            }else {
                                $scope.marksed.splice(k, 1, o);
                            }
                        }
                        $scope.showIndex= -1;
                    }else {
                        if ($scope.marksed.indexOf(o) == -1){
                            $scope.markseding.push(o);
                            $scope.marksed.push(o);
                        }
                    }
                }
                
                // 标签列表按钮事件
                $scope.makeSure= function (t, n) {
                    if (t == 1){    // 确定按钮
                    }else if (t == 0){  // 取消按钮
                        angular.forEach($scope.markseding, function (item, key) {
                            angular.forEach($scope.marksed, function (it, k) {
                                if (item.name == it.name && item.type == it.type){
                                    $scope.marksed.splice(k,1);
                                }
                            })
                        })
                    }else if(t == -1){     // 清空按钮
                        angular.forEach($scope.marksed, function (it, k) {
                            if (n == it.type){
                                delete $scope.marksed[k];
                            }
                        })
                    }else {
                        $scope.marksed= [];
                    }
                    $scope.showIndex= -1;
                    $scope.markseding= [];
                }

                // 已选和未选
                $scope.clicked= function () {
                    
                }
            }
        }
    }]);

    /**
     * 选项卡指令封装
     *
     */
    app.directive('tabs', [
        '$timeout',
        function ($timeout) {
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                tabsdata: '=',
                pageUrl: '='
            },
            templateUrl: '/client/components/public/template/tabsTpl.html',
            link: function ($scope, element, attrs) {
                $scope.pageUrl= '';     // 内嵌选项卡页面url
                $scope.showitemid= (!!$scope.showitemid||$scope.showitemid==0)? $scope.showitemid: -1;
                // 切换选项卡
                $scope.changeTabs= function (t, url) {
                    if (t != -1 && !!url){
                        $scope.pageUrl= url;
                        $scope.showitemid= t;
                    }else if (t == -1){
                        $scope.showitemid= t;
                    }
                }

                // 关闭选项卡
                $scope.closeTab= function (index,$event) {
                    $event.stopPropagation();
                    if ($scope.tabsdata.length >= 2){
                        if ($scope.tabsdata.length-1 != index) {
                            $scope.tabsdata.splice(index, 1);
                            if ($scope.showitemid == index){
                                $scope.showitemid = index;
                            } else if ($scope.showitemid > index){
                                $scope.showitemid-= 1;
                            }
                        }else if ($scope.tabsdata.length-1 == index) {
                            $scope.tabsdata.splice(index, 1);
                            $scope.showitemid= $scope.showitemid == index? index-1: $scope.showitemid;
                        }
                    }else {
                        $scope.tabsdata.splice(index, 1);
                        $scope.showitemid= -1;
                    }
                }

                // 监听选项卡数组
                $scope.$watch('tabsdata', function (newVal, oldVal, e) {
                    if (!!newVal && newVal.length != 0){
                        if (newVal.length > oldVal.length){     // 打开选项卡
                            $scope.showitemid= newVal.length-1;
                            $scope.pageUrl= newVal[$scope.showitemid].url;
                        } else if (newVal.length == oldVal.length) {
                            var newItem= {};
                            angular.forEach(newVal, function (item, k) {
                                if (item.url.indexOf('?_') != -1){
                                    var timeStr= item.url.substring(item.url.lastIndexOf('?_')+2);
                                    if (!!newItem.url){
                                        if (newItem.timeStr < timeStr){
                                            newItem.url= item.url;
                                            newItem.index= k;
                                            newItem.timeStr= timeStr;
                                        }
                                    } else {
                                        newItem.url= item.url;
                                        newItem.index= k;
                                        newItem.timeStr= timeStr;
                                    }
                                }
                            })
                            $scope.showitemid= newItem.index;
                            $scope.pageUrl= newVal[$scope.showitemid].url;
                        } else {
                            $scope.pageUrl= newVal[$scope.showitemid].url;
                        }
                    }
                    // 计算设置选项卡长度
                    $timeout(function () {
                        var ulWidth= element.find('ul')[0].clientWidth - 20 -57;
                        var liWidth= 0;
                        if ((newVal.length + 1) * 157 > ulWidth){
                            liWidth= ulWidth / newVal.length - 7 - 20;
                            var liArr= element.find('ul li');
                            angular.forEach(liArr, function (item, k) {
                                if (k != 0){
                                    angular.element(item).css('width', liWidth+'px');
                                }
                            })
                        }
                    }, 50);
                }, true)

                // 清空所有选项卡
                $scope.clearAllTabs= function () {
                    $scope.tabsdata= [];
                    $scope.showitemid= -1;
                }
            }
        }
    }]);

    /*
    *
    * 分页指令逻辑处理
    *
    * */
    app.factory('uiPager', [function(){
        return {
            gen: function(pager, opts){
                var pagi = {};
                if(!pager){
                    pagi.totalPageLl = [];
                    pagi.totalPage = 0;
                    pagi.totalCount = 0;
                    pagi.pageNum = 0;
                    pagi.pageSize = 0;

                    pagi.style = {};
                    pagi.style.btnClass = 'btn';

                    // first previous next last / buttons disabled
                    pagi.ctrl = {};
                    pagi.ctrl.isChoosePageDisabled = true;
                    pagi.ctrl.isFirstPageDisabled = true;
                    pagi.ctrl.isPrevPageDisabled = true;
                    pagi.ctrl.isNextPageDisabled = true;
                    pagi.ctrl.isLastPageDisabled = true;

                    return pagi;
                }

                // current page
                pagi.pageNum = pager.pageNum || 0;
                // number per page
                pagi.pageSize = pager.pageSize || 10;
                pagi.totalCount = pager.totalCount || 0;
                // no records
                if(!pagi.totalCount)
                    pagi.pageNum = 0;

                pagi.totalPage = this.getTotalPage(pagi.totalCount, pagi.pageSize);
                pagi.totalPageLl = this.getTotalPageLl(pagi.totalPage, pagi.pageNum, opts);

                pagi.targetPageChoosed = _.find(pagi.totalPageLl, function(it){
                    return it.pageNum == pagi.pageNum;
                });

                pagi.style = {};
                pagi.style.btnClass = 'btn btn-info';

                // first previous next last
                pagi.ctrl = {};
                pagi.ctrl.isFirstPageDisabled = pagi.totalCount == 0 || pagi.pageNum == 1;
                pagi.ctrl.isPrevPageDisabled = pagi.pageNum <= 1;
                pagi.ctrl.isNextPageDisabled = pagi.pageNum == pagi.totalPage;
                pagi.ctrl.isLastPageDisabled = pagi.totalPage <= 1 || pagi.pageNum == pagi.totalPage;
                pagi.ctrl.isChoosePageDisabled = pagi.totalPage <= 1;

                return pagi;
            },

            refresh: function(pagi){
                pagi.totalPage = this.getTotalPage(pagi.totalCount, pagi.pageSize);
                pagi.totalPageLl = this.getTotalPageLl(pagi.totalPage, pagi.pageNum);
            },

            getTotalPageLl: function(totalPage, pageNum, opts){
                return _.map(_.range(1, totalPage + 1), function(it){
                    var pagiBtnClass = 'btn';
                    if(opts && opts.defaultBtnClass)
                        pagiBtnClass = opts.defaultBtnClass;

                    // model with button style
                    // use ng-repeat to render different buttons
                    var one = {};
                    one.btnClass = pagiBtnClass;
                    one.pageNum = it;

                    if(pageNum == it){
                        one.btnClass = 'btn btn-info';
                        if(opts && opts.currentBtnClass)
                            one.btnClass = opts.currentBtnClass;
                    }

                    return one;
                });
            },

            getTotalPage: function(totalCount, pageSize){
                var r = totalCount % pageSize;
                var r2 = totalCount / pageSize;
                var result = r == 0 ? r2 : r2 + 1;
                return Math.floor(result);
            }
        };
    }]);

    /*
    * 分页指令
    * */
    app.directive('uiPagiNew', ['uiPager', function(pager){
        return {
            restrict: 'A',

            templateUrl: '/client/components/public/template/pagisel_new.html',
            replace: false,

            scope: {
                pager: '=',

                onChangePage: '&'
            },

            link: function(scope, el, attrs){
                var opts = scope.$eval(attrs.uiPagi) || {};
                scope.$watch('pager', function(it){
                    scope.pagi = pager.gen(it, opts);
                }, true);
            }
        };
    }]);

    /*
    * 无遮罩弹窗指令
    * */
    app.directive('noCapWin', [ function () {
        return {
            restrict: 'AE',
            templateUrl: '/client/components/public/template/noCapWinTpl.html',
            replace: false,
            scope: {
                nocapdata: '=',
                winshow: '='
            },

            link: function($scope, el, attrs){
                $scope.onChangePage= function (cp, event) {
                    $scope.nocapdata.changePage(cp, event);
                }
            }
        };
    }]);
    
    /*
    * 分页表格指令
    * */
    app.directive('tablepage', [function () {
        return {
            restrice: 'AE',
            replace: false,
            scope: {
                thead: '=',
                pager: '=',
                changePage: '&'
            },
            templateUrl: '/client/components/public/template/tablePage.html',
            link: function ($scope, el, attr) {
                $scope.onChangePage= function (cp, event) {
                    $scope.changePage({cp: cp, event: event});
                }
            }
        }
    }]);

    /*
    * 无序列表指令
    * */
    app.directive('ullist', [function () {
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                data: '='
            },
            template: '<div><ul><li ng-repeat="x in data"><span ng-bind="x.title"></span><span ng-bind="x.date" class="float-rt" style="margin-right:20px;"></span></li></ul></div>',
            link: function ($scope, el, attr) {
            }
        }
    }]);

    /**
     * 富文本指令
     */
    app.directive('ngEditor', [function () {
        return {
            restrict: 'AE',
            replace: true,
            template: '<div><textarea id="container" ng-model="content"></textarea></div>',
            link: function ($scope) {
                var initConfig= {
                    initialFrameWidth:900,  // 富文本初始宽度
                    maximumWords:4000   // 允许最大字符数
                }
                initConfig= !!$scope.config? $scope.config: initConfig;
                // 初始化之前先销毁富文本实例，防止第二次初始化时，富文本无法渲染
                UE.delEditor('container');
                // 初始化
                $scope.editor= UE.getEditor('container', initConfig);
                // 绑定数据同步
                $scope.editor.ready(function () {
                    var editorFlag= true;
                    $scope.$watch('content', function (newVal) {
                        if (!!newVal && newVal !== $scope.editor.getContent()){
                            editorFlag= false;
                            $scope.editor.setContent(newVal);
                        }
                    })
                    // 编辑器内容改变事件
                    $scope.editor.addListener('contentChange', function () {
                        if (editorFlag){
                            $scope.content= $scope.editor.getContent();
                            if(!$scope.$root.$$phase){
                                $scope.$apply();
                            }
                        }else {
                            editorFlag= true;
                        }
                    })
                })
                
                // 光标处插入指定内容
                $scope.insetContent= function (str) {
                    $scope.editor.execCommand('inserthtml', str);
                }
                
                // 获取富文本内容
                $scope.getContent= function (t) {
                    var content= '';
                    if (t === 'html'){
                        content= $scope.editor.getContent();
                    } else {
                        content= $scope.editor.getContentTxt();
                    }
                    return content;
                }
                
                // 编辑器获取焦点
                $scope.editorFocus= function (end) {
                    $scope.editor.focus(end)
                }

                // 编辑器不可编辑
                $scope.setDisabled= function () {
                    $scope.editor.setDisabled();
                }
                // 设置编辑器可编辑
                $scope.setEnabled= function () {
                    $scope.editor.setEnabled();
                }
            }
        }
    }]);

    /**
     * 日期时间指令
     */
    app.directive('dateTime', [function () {
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                datetime: '=',
                dateConfig: '='
            },
            template: '<input type="text" ng-model="datetime.value" placeholder={{datetime.text}} ng-readonly="true" class="form-control"/></span>',
            link: function ($scope, elem, attr, ctrl) {
                var options= {
                    duration: 'fast',
                    dateFormat: 'yy-mm-dd',
                    changeMonth: true,
                    changeYear: true,
                    showMonthAfterYear: true,
                    yearSuffix: ''
                }
                var getOptions = function(){
                    return angular.extend(options, $scope.dateConfig);
                };
                (function(){
                    var opts = getOptions();
                    opts.onSelect = function(value, picker){
                        if (opts.dateFormat.indexOf('ss') == -1) {
                            $scope.datetime.value= value;
                        }else {
                            var date= new Date();
                            $scope.datetime.value= value+" "+dateFormmate(date);
                        }
                        $scope.$apply();
                    };
                    elem.datepicker('destroy');
                    elem.datepicker(opts);
                })();

                function dateFormmate(date) {
                    var h= date.getHours()>= 10? date.getHours(): '0'+ date.getHours(),
                        m= date.getMinutes()>= 10? date.getMinutes(): '0'+ date.getMinutes(),
                        s= date.getSeconds()>= 10? date.getSeconds(): '0'+ date.getSeconds();
                    return h+ ':'+ m+ ':'+ s;
                }
            }
        }
    }]);

    /*
    * 下拉选择框
    *    $scope.firstSelectObj= {
    *        options: $scope.datas,
    *        selected: $scope.datas[0].id,
    *        changeFun: $scope.callback
    *    }
    * */
    app.directive('ngSelect', [function () {
        return {
            restrict: 'AE',
            replace: true,
            scope: {
                selectObj: '='
            },
            template: "<select ng-change='changeFun()' ng-model='selectObj.selected' style='padding:0;box-sizing:border-box !important;' class='form-control'><option value='' ng-if='!selectObj.selected || isEmpty'>请选择</option><option ng-selected='x.id == selectObj.selected' value='{{x.id}}' ng-repeat='x in selectObj.options track by $index' ng-bind='x.name'></option></select>",
            link: function ($scope, elem, attr, ctrl) {
                if (!$scope.selectObj.selected){
                    $scope.isEmpty= true;
                }
                $scope.changeFun= function () {
                    $scope.selectObj.changeFun();
                }
            }
        }
    }])

    // 文本上下跑马灯特效封装
    app.directive('textScroll', ['$rootScope', '$interval', '$timeout', function ($rootScope, $interval, $timeout) {
        return {
            restrict: 'AE',
            replace: 'true',
            scope: {
                textList: '=',
                speed: '@',
                interval: '@',
                scrollType: '@'
            },
            template: '<div style="position: relative;"><ul ng-style="pos"><li class="scroll" ng-repeat="x in textList track by $index"><span ng-bind="x.text"></span></li></ul></div>',
            link: function ($scope, elem, attr, ctrl) {
                $scope.speed= !!$scope.speed? $scope.speed: 1000;
                $scope.interval= !!$scope.interval&&$scope.interval>$scope.speed? $scope.interval: Number($scope.speed)+500;
                $scope.speedStop= ($scope.speed/1000).toFixed(1);
                var scrollType= !!$scope.scrollType? $scope.scrollType: 'toUp'; // 默认向上滚动
                // 如果向下滚动
                if (scrollType === 'toDown'){
                    $timeout(function () {
                        $scope.pos= {
                            'position': 'absolute',
                            'bottom': -elem.find('ul>li').height() + 'px'
                        }
                    }, 0)
                }
                // 当内容大于1条是才滚动
                if ($scope.textList.length > 1){
                    var inter= $interval(function () {
                        scrolling(elem.find('ul')[0], scrollType);
                    }, $scope.interval);
                    $rootScope.intervalArr.push(inter);
                }

                // 滚动
                function scrolling(node, type){
                    var scrollh= -angular.element(node).find('li').height() + 'px';
                    if (type === 'toUp'){   //向上滚动
                        $timeout(function () {
                            node.style.transition= 'none';
                            node.style.transform= 'none';
                            var obj= $scope.textList[0];
                            $scope.textList.push(obj);
                            $scope.textList.shift();
                        }, Number($scope.speed));
                    }else if (type === 'toDown'){//向下滚动
                        scrollh= angular.element(node).find('li').height() + 'px';
                        $timeout(function () {
                            var obj= $scope.textList[$scope.textList.length-1];
                            $scope.textList.unshift(obj);
                            $scope.textList.pop();
                            node.style.transition= 'none';
                            node.style.transform= 'none';
                        }, Number($scope.speed));
                    }
                    node.style.transform= 'translate3d(0, '+scrollh+', 0)';
                    node.style.transition= 'transform '+$scope.speedStop+'s';
                }
            }
        }
    }])


})()